import LifeserviceCore from './core/index.js';
import { AuthService, RouterService, ApiService, I18nService, NotificationService, ErrorService, LoggerService, DemoService } from './core/index.js';
import * as utils from './utils/index.js';
import { messages as defaultMessages } from './utils/i18n/index.js';
import { Service, LifeserviceConfig, ServiceOptions } from './types/index.js';

// 创建框架实例
const lifedervice = new LifeserviceCore();

/**
 * Vue插件安装方法
 * 增强以支持后台管理系统特性
 */
function install(app, options = {}) {
  // 合并配置
  const config = { 
    ...LifeserviceConfig, 
    admin: {
      ...LifeserviceConfig.admin,
      ...(options.admin || {})
    },
    ...options 
  };
  
  // 配置框架
  Object.entries(config).forEach(([key, value]) => {
    if (key !== 'admin') {
      lifedervice.setConfig(key, value);
    }
  });
  
  // 配置admin部分
  if (config.admin) {
    Object.entries(config.admin).forEach(([key, value]) => {
      lifedervice.setConfig(`admin.${key}`, value);
    });
  }
  
  // 自动注册核心服务
  registerCoreServices(lifedervice);
  
  // 注册全局属性
  app.config.globalProperties.$lifeservice = lifedervice;
  app.config.globalProperties.$auth = null; // 将在启动时设置
  app.config.globalProperties.$routerService = null; // 将在启动时设置
  
  // 提供注入
  app.provide('lifeservice', lifedervice);
  app.provide('$auth', null); // 将在启动时设置
  app.provide('$routerService', null); // 将在启动时设置
  
  // 注册全局组件和指令
  registerGlobalComponents(app);
  registerGlobalDirectives(app, lifedervice);
  
  // 注入全局错误处理
  if (config.errorHandler) {
    app.config.errorHandler = config.errorHandler;
  }
  
  // 处理路由
  if (options.router) {
    setupRouter(options.router, lifedervice);
  }
  
  // 自动启动
  if (config.autoBoot) {
    lifedervice.boot();
    
    // 启动后设置全局auth和routerService引用
    const authService = lifedervice.get('auth');
    const routerService = lifedervice.get('router');
    const demoService = lifedervice.get('demo');
    
    if (authService) {
      app.config.globalProperties.$auth = authService;
      app.provide('$auth', authService);
    }
    
    if (routerService) {
      app.config.globalProperties.$routerService = routerService;
      app.provide('$routerService', routerService);
    }
    
    if (demoService) {
      app.config.globalProperties.$demo = demoService;
      app.provide('$demo', demoService);
    }
  }
  
  // 注册Vue实例方法
  registerVueInstanceMethods(app);
  
  console.log('LifeService framework installed successfully for admin system');
}

/**
 * 注册核心服务
 */
function registerCoreServices(container) {
  // 注册认证服务
  container.register('auth', AuthService, {
    priority: 100,
    singleton: true
  });
  
  // 注册日志服务
  container.register('logger', LoggerService, {
    priority: 99,
    singleton: true
  });
  
  // 注册国际化服务
  container.register('i18n', I18nService, {
    priority: 98,
    singleton: true,
    options: {
      defaultMessages
    }
  });
  
  // 注册通知服务
  container.register('notification', NotificationService, {
    priority: 96,
    singleton: true,
    dependencies: ['i18n']
  });
  
  // 注册API服务
  container.register('api', ApiService, {
    priority: 95,
    singleton: true,
    dependencies: ['i18n', 'error']
  });
  
  // 注册错误处理服务
  container.register('error', ErrorService, {
    priority: 94,
    singleton: true,
    dependencies: ['notification', 'logger']
  });
  
  // 注册路由服务
  container.register('router', RouterService, {
    priority: 90,
    dependencies: ['auth'],
    singleton: true
  });
  
  // 注册演示服务
  container.register('demo', DemoService, {
    priority: 50,
    singleton: true,
    dependencies: ['auth', 'api', 'i18n', 'notification', 'error', 'logger']
  });
}

/**
 * 注册全局组件
 */
function registerGlobalComponents(app) {
  // 这里可以注册后台管理系统常用的全局组件
  // 例如：表格、表单、对话框等
  
  // 示例：注册权限检查组件
  app.component('PermissionGuard', {
    props: {
      permission: String,
      role: String,
      fallback: {
        type: Boolean,
        default: false
      }
    },
    setup(props, { slots }) {
      const auth = inject('$auth');
      
      // 检查权限
      const hasPermission = computed(() => {
        if (!auth) return props.fallback;
        
        if (props.permission) {
          return auth.hasPermission(props.permission);
        }
        
        if (props.role) {
          return auth.hasRole(props.role);
        }
        
        return true;
      });
      
      return () => hasPermission.value ? slots.default?.() : slots.fallback?.() || null;
    }
  });
}

/**
 * 注册全局指令
 */
function registerGlobalDirectives(app, container) {
  // 权限指令
  app.directive('permission', {
    mounted(el, binding) {
      const auth = container.get('auth');
      const permission = binding.value;
      
      if (permission && auth && !auth.hasPermission(permission)) {
        el.style.display = 'none';
      }
    },
    updated(el, binding) {
      const auth = container.get('auth');
      const permission = binding.value;
      
      if (permission && auth) {
        el.style.display = auth.hasPermission(permission) ? '' : 'none';
      }
    }
  });
  
  // 角色指令
  app.directive('role', {
    mounted(el, binding) {
      const auth = container.get('auth');
      const role = binding.value;
      
      if (role && auth && !auth.hasRole(role)) {
        el.style.display = 'none';
      }
    },
    updated(el, binding) {
      const auth = container.get('auth');
      const role = binding.value;
      
      if (role && auth) {
        el.style.display = auth.hasRole(role) ? '' : 'none';
      }
    }
  });
}

/**
 * 设置路由
 */
function setupRouter(router, container) {
  // 获取路由服务并初始化
  const routerService = container.get('router');
  if (routerService) {
    routerService.init(router);
  }
  
  // 路由加载完成事件
  router.isReady().then(() => {
    console.log('Router is ready, initializing admin services');
  });
}

/**
 * 注册Vue实例方法
 */
function registerVueInstanceMethods(app) {
  // 添加全局方法
  app.config.globalProperties.$hasPermission = function(permission) {
    const auth = this.$auth || this.$lifeservice.get('auth');
    return auth ? auth.hasPermission(permission) : false;
  };
  
  app.config.globalProperties.$hasRole = function(role) {
    const auth = this.$auth || this.$lifeservice.get('auth');
    return auth ? auth.hasRole(role) : false;
  };
  
  app.config.globalProperties.$isLoggedIn = function() {
    const auth = this.$auth || this.$lifeservice.get('auth');
    return auth ? auth.isLoggedIn() : false;
  };
  
  app.config.globalProperties.$getUserInfo = function() {
    const auth = this.$auth || this.$lifeservice.get('auth');
    return auth ? auth.getUserInfo() : null;
  };
  
  // 国际化相关全局方法
  app.config.globalProperties.$t = function(...args) {
    const i18n = this.$lifeservice.get('i18n');
    return i18n ? i18n.t(...args) : '';
  };
  
  app.config.globalProperties.$setLocale = function(...args) {
    const i18n = this.$lifeservice.get('i18n');
    return i18n ? i18n.setLocale(...args) : null;
  };
  
  app.config.globalProperties.$getLocale = function() {
    const i18n = this.$lifeservice.get('i18n');
    return i18n ? i18n.getLocale() : null;
  };
  
  // 通知相关全局方法
  app.config.globalProperties.$notify = function(...args) {
    const notification = this.$lifeservice.get('notification');
    return notification ? notification.notify(...args) : null;
  };
  
  app.config.globalProperties.$info = function(...args) {
    const notification = this.$lifeservice.get('notification');
    return notification ? notification.info(...args) : null;
  };
  
  app.config.globalProperties.$success = function(...args) {
    const notification = this.$lifeservice.get('notification');
    return notification ? notification.success(...args) : null;
  };
  
  app.config.globalProperties.$warning = function(...args) {
    const notification = this.$lifeservice.get('notification');
    return notification ? notification.warning(...args) : null;
  };
  
  app.config.globalProperties.$error = function(...args) {
    const notification = this.$lifeservice.get('notification');
    return notification ? notification.error(...args) : null;
  };
  
  app.config.globalProperties.$confirm = function(...args) {
    const notification = this.$lifeservice.get('notification');
    return notification ? notification.confirm(...args) : Promise.reject();
  };
  
  app.config.globalProperties.$prompt = function(...args) {
    const notification = this.$lifeservice.get('notification');
    return notification ? notification.prompt(...args) : Promise.reject();
  };
  
  app.config.globalProperties.$loading = function(...args) {
    const notification = this.$lifeservice.get('notification');
    return notification ? notification.loading(...args) : null;
  };
  
  app.config.globalProperties.$closeLoading = function() {
    const notification = this.$lifeservice.get('notification');
    if (notification) {
      notification.closeLoading();
    }
  };
  
  // 日志相关全局方法
  app.config.globalProperties.$log = function(...args) {
    const logger = this.$lifeservice.get('logger');
    return logger ? logger.log(...args) : null;
  };
  
  app.config.globalProperties.$debug = function(...args) {
    const logger = this.$lifeservice.get('logger');
    return logger ? logger.debug(...args) : null;
  };
  
  app.config.globalProperties.$infoLog = function(...args) {
    const logger = this.$lifeservice.get('logger');
    return logger ? logger.info(...args) : null;
  };
  
  app.config.globalProperties.$warn = function(...args) {
    const logger = this.$lifeservice.get('logger');
    return logger ? logger.warning(...args) : null;
  };
  
  app.config.globalProperties.$errorLog = function(...args) {
    const logger = this.$lifeservice.get('logger');
    return logger ? logger.error(...args) : null;
  };
  
  // 错误处理相关全局方法
  app.config.globalProperties.$handleError = function(...args) {
    const errorService = this.$lifeservice.get('error');
    return errorService ? errorService.handleError(...args) : null;
  };
}

// 确保导入inject和computed
import { inject, computed } from 'vue';

// 导出框架
const LifeService = {
  install,
  lifedervice,
  Service,
  utils,
  createInstance: () => new LifeserviceCore(),
  version: '1.0.0',
  DemoService
};

// 导出默认值和命名导出
export default LifeService;
export { LifeserviceCore, Service, utils, AuthService, RouterService, ApiService, I18nService, NotificationService, ErrorService, LoggerService, DemoService };